package collector

import (
	"time"

	"gitee.com/openeuler/uos-libvirtd-exporter/slogx"
	"libvirt.org/go/libvirt"
)

// LogCollector provides standardized logging for collectors
type LogCollector struct {
	name string
}

// NewLogCollector creates a new log collector for the specified collector type
func NewLogCollector(name string) *LogCollector {
	return &LogCollector{name: name}
}

// LogCollectionStart logs the start of metric collection
func (l *LogCollector) LogCollectionStart(domainName string) {
	slogx.Debug("Starting metric collection",
		"collector", l.name,
		"domain", domainName)
}

// LogCollectionSuccess logs successful metric collection
func (l *LogCollector) LogCollectionSuccess(domainName string, duration time.Duration, metricCount int) {
	slogx.Debug("Metric collection completed successfully",
		"collector", l.name,
		"domain", domainName,
		"duration_ms", duration.Milliseconds(),
		"metrics_collected", metricCount)
}

// LogCollectionError logs collection errors with context
func (l *LogCollector) LogCollectionError(domainName string, metric string, err error, duration time.Duration) {
	if IsDomainNotRunning(err) {
		slogx.Debug("Skipping non-running domain for metrics",
			"collector", l.name,
			"domain", domainName,
			"metric", metric,
			"duration_ms", duration.Milliseconds())
	} else {
		slogx.Warn("Failed to collect metrics",
			"collector", l.name,
			"domain", domainName,
			"metric", metric,
			"error", err,
			"duration_ms", duration.Milliseconds())
	}
}

// LogDomainState logs domain state information
func (l *LogCollector) LogDomainState(domainName string, state libvirt.DomainState) {
	stateStr := domainStateToString(state)
	slogx.Debug("Domain state check",
		"collector", l.name,
		"domain", domainName,
		"state", stateStr,
		"state_code", int(state))
}

// LogCollectionSkip logs when collection is skipped
func (l *LogCollector) LogCollectionSkip(domainName string, reason string) {
	slogx.Debug("Skipping metric collection",
		"collector", l.name,
		"domain", domainName,
		"reason", reason)
}

// domainStateToString converts domain state to human readable string
func domainStateToString(state libvirt.DomainState) string {
	switch state {
	case libvirt.DOMAIN_NOSTATE:
		return "no_state"
	case libvirt.DOMAIN_RUNNING:
		return "running"
	case libvirt.DOMAIN_BLOCKED:
		return "blocked"
	case libvirt.DOMAIN_PAUSED:
		return "paused"
	case libvirt.DOMAIN_SHUTDOWN:
		return "shutdown"
	case libvirt.DOMAIN_SHUTOFF:
		return "shutoff"
	case libvirt.DOMAIN_CRASHED:
		return "crashed"
	case libvirt.DOMAIN_PMSUSPENDED:
		return "pm_suspended"
	default:
		return "unknown"
	}
}
